﻿using DeHeng_Mes.Dao;
using DeHeng_Mes.Dao.PlcDao;
using DeHeng_Mes.Model;
using DeHeng_Mes.Model.Boss;
using DeHeng_Mes.Model.ConfigModel;
using DeHeng_Mes.Model.OrderSingleton;
using DeHeng_Mes.Model.Singleton;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.PlcService;
using DeHeng_Mes.Utils;
using FluentFTP;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using S7.Net;
using S7.Net.Types;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Shapes;
using System.Xml.Linq;
using DateTime = System.DateTime;
using MappingTable = DeHeng_Mes.Utils.MappingTable;
using Path = System.IO.Path;

namespace DeHeng_Mes.Service
{
    public class PlcServicees
    {
        #region 成员实例
        PlcDao plcDao = new PlcDao();
        OrderDao orderDao = new OrderDao();
        ProductionPowerDao productionPowerDao = new ProductionPowerDao();
        List<PlcOrderConfigModel> readPlcList = PlcOrderConfigModelList.ReadPlcList;
        ExitService exitService = new ExitService();
        #endregion

        /// <summary>
        /// 获取当日能耗和产量
        /// </summary>
        /// <param name="isTimer"></param>
        public void GetPowerAndProdution(bool isTimer)
        {
            // 检查连接状态并查询工单
            foreach (var item in PlcConnectionManager.plcContainer)
            {
                // 未连接跳出本层
                if (!item.isConnected)
                    continue;

                // 获取Plc数据
                Dictionary<object, Type> dictionary = MappingTable.PlcMapping(item.plc, item.name);

                // 获取当前日期
                DateTime currentDate = DateTime.Now;

                // 获取天
                DateTime previousDate = isTimer ? currentDate.AddDays(-1) : currentDate;

                string day = previousDate.Day.ToString();

                // 获取当前年月日
                string date = $"{previousDate.Year}{previousDate.Month:D2}{previousDate.Day:D2}";

                // 判断当前plcName，执行不同方法
                switch (item.name)
                {
                    case "DOOR-01":
                        break;
                    case "DOOR-02":
                        // 执行当日产量采集
                        Dictionary<string, object> productionDic = plcDao.GetFieldValues(dictionary, "Production");

                        // 初始化产量
                        string production = string.Empty;

                        // 获取产量
                        foreach (var productions in productionDic)
                        {
                            if (productions.Key.Replace("Day", "").Equals(day))
                            {
                                production = productions.Value.ToString();
                            }
                        }

                        // 存入当天产量数据
                        if (!string.IsNullOrEmpty(production))
                        {
                            // 判断产量数据是否保存
                            if (productionPowerDao.ProductionIsSave(item.name, date, production))
                                // 执行更新操作
                                productionPowerDao.UpdateProduction(item.name, date, production);
                            else
                                //执行插入操作
                                productionPowerDao.ProductionSave(item.name, date, production);
                        }
                        break;
                }

                // 执行当日能耗采集
                Dictionary<string, object> powerDic = plcDao.GetFieldValues(dictionary, "Power");

                // 初始化当天能耗
                string power = string.Empty;

                // 获取当天能耗
                foreach (var powers in powerDic)
                {
                    if (powers.Key.Replace("Day", "").Equals(day))
                    {
                        power = powers.Value.ToString();
                    }
                }

                // 存入当天能耗数据
                if (!string.IsNullOrEmpty(power))
                {
                    // 判断能耗数据是否保存
                    if (productionPowerDao.PowerIsSave(item.name, date, power))
                        // 执行更新操作
                        productionPowerDao.UpdatePower(item.name, date, power);
                    else
                        //执行插入操作
                        productionPowerDao.PowerSave(item.name, date, power);
                }
            }
        }

        /// <summary>
        /// 0点监控
        /// </summary>
        public async Task Timer()
        {
            while (true)
            {
                // 获取当前时间
                DateTime now = DateTime.Now;

                // 判断是否为凌晨0点
                // 判断是否为凌晨0点
                if (now.Hour == 0 && now.Minute == 0 && now.Second == 0)
                {
                    GetPowerAndProdution(true);
                }
                await Task.Delay(900);
            }
        }

        /// <summary>
        /// 存储拉铆数据
        /// </summary>
        /// <returns></returns>
        public async Task ReadRiveteData()
        {
            List<string> strings = new List<string>()
            {
                "5_6",
                "7",
                "8",
                "9-1",
                "10",
                "11_12",
                "13",
                "14",
                "15_16",
                "17_18",
            };

            while (true)
            {
                try
                {
                    foreach (var item in strings)
                    {
                        await ReveteConnection(item);

                        await Task.Delay(1000);
                    }

                    // 延迟5秒读取
                    await Task.Delay(5000);
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogText($"读取并保存拉铆数据发生异常：原因是：{ex.Message}");
                }
            }
        }

        private async Task ReveteConnection(string count)
        {

            try
            {
                // 初始化文件夹路径
                string directory = $@"D:\LM\before\{count}\Data_Info\{DateTime.Now.ToString("yyyy")}{DateTime.Now.ToString("MM")}\{DateTime.Now.ToString("yyyy")}{DateTime.Now.ToString("MM")}{DateTime.Now.ToString("dd")}";

                if (Directory.Exists(directory))
                {
                    // 获取目录下所有CSV文件路径
                    string[] csvFiles = Directory.GetFiles(directory, "*.csv");

                    foreach (string filePath in csvFiles)
                    {

                        if (filePath.Contains("_Save"))
                            continue;

                        // 提取文件名和扩展名
                        string fileName = Path.GetFileNameWithoutExtension(filePath);
                        string extension = Path.GetExtension(filePath); // 如 ".csv"

                        // 构建新文件名：原文件名 + "_Save" + 扩展名
                        string newFileName = $"{fileName}_Save{extension}";
                        string newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName);

                        // 调用方法读取文件数据
                        Dictionary<string, string[]> csvData = await CsvReaderHelper.ReadCsv(filePath, "二维码");

                        List<TraceRivete> traceRivetes = new List<TraceRivete>();

                        // 实例化存储类
                        TraceRivete traceRivete = null;

                        // 循环存储
                        for (int i = 0; i <= csvData["二维码"].Length - 1; i++)
                        {
                            traceRivete = new TraceRivete();

                            traceRivete.Result = csvData["结果"][i];

                            traceRivete.DataTime = $"{csvData["日期"][i]} {csvData["时间"][i]}";

                            traceRivete.Pulling = csvData["拉力"][i];

                            traceRivete.PullingMax = csvData["拉力上限"][i];

                            traceRivete.PullingMin = csvData["拉力下限"][i];

                            traceRivete.Displacement = csvData["位移量"][i];

                            traceRivete.DisplacementMax = csvData["位移上限"][i];

                            traceRivete.DisplacementMin = csvData["位移下限"][i];

                            traceRivete.TraceId = csvData["二维码"][i].Equals("null") ? csvData["批次"][i] : csvData["二维码"][i];

                            traceRivete.PointNo = csvData["点位编号"][i];

                            traceRivete.PointCount = csvData["点位计数"][i];

                            traceRivete.ToolNo = csvData["枪号"][i];

                            traceRivete.Station = csvData["工位号"][i];

                            traceRivetes.Add(traceRivete);

                            // 调用存储
                            if (!orderDao.RiveteDataIsSave(traceRivete.TraceId, traceRivete.PointCount, traceRivete.Station))
                                orderDao.SaveRiveteData(traceRivete);
                        }

                        Tools.ProduceLogText($"成功保存{csvData["二维码"].Length}条拉铆数据，关联码为[{traceRivete.TraceId}],工位[{traceRivete.Station}]");

                        try
                        {
                            // 重命名文件（如果已存在则跳过或覆盖）
                            if (!File.Exists(newFilePath))
                            {
                                File.Move(filePath, newFilePath);

                                ViewService.CodeBandingOrder(traceRivete.Station, traceRivete.TraceId);

                                string result = fileName.Split('_')[2];

                                // 过站数据绑定
                                if (!orderDao.ProcessDataFromCsvIsSave(traceRivete.TraceId, traceRivete.Station))
                                {
                                    OrderStatus orderStatus = Tools.GetOrder(traceRivete.Station, traceRivete.TraceId, orderDao);

                                    PartProcess partProcess = orderDao.SaveProcessDataFromCsv(traceRivete, result);

                                    ViewService.CodeBandingStationPush(partProcess, orderStatus);
                                }                             

                                exitService.OrderProduction(traceRivete.Station);

                                _ = Task.Run(() => { ViewService.InsertLineMesData(traceRivete.TraceId, traceRivete.Station, traceRivetes); });
                            }
                            else
                            {
                                Tools.ProduceLogTextError($"文件已存在，跳过: {newFileName}");

                                File.Delete(filePath);
                            }
                        }
                        catch (IOException ex)
                        {
                            Tools.ProduceLogTextError($"标签打入失败: {ex.Message}");
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Tools.ProduceLogText($"读取并保存拉铆数据发生异常：原因是：{ex.Message}");
            }

        }

        /// <summary>
        /// 读取压铆的CSV数据文件
        /// </summary>
        /// <returns></returns>
        public async Task ReadCSVData()
        {

            while (true)
            {
                try
                {
                    List<string> ips = new List<string>()
                    {
                        "192.168.10.11",
                        "192.168.10.12",
                    };

                    foreach (var ip in ips)
                    {
                        await YMConnection(ip);
                    }

                    // 延迟5秒读取
                    await Task.Delay(5000);
                }
                catch (Exception ex)
                {
                    /*Tools.ProduceLogText($"读取并保存压铆数据发生异常：原因是：{ex.Message}");*/
                }
            }


        }

        private async Task YMConnection(string ip)
        {

            DateTime dateTime = DateTime.Now;

            string date = $"{dateTime.ToString("yyyy")}{dateTime.ToString("MM")}";

            // 初始化日期
            string date1 = $"{dateTime.ToString("yyyy")}{dateTime.ToString("MM")}{dateTime.ToString("dd")}";

            // 初始化文件夹路径
            string directory = $@"\\{ip}\ym\before\Data_info\{date}\{date1}";

            string curveDirectory = $@"\\{ip}\ym\before\Data_Curve\{date}\{date1}";

            await ClinchInfo(directory);

            //ClinchCurve(curveDirectory);
        }

        private async void ClinchCurve(string curveDirectory)
        {
            if (Directory.Exists(curveDirectory))
            {
                try
                {
                    // 获取目录下所有CSV文件路径
                    string[] csvFiles = Directory.GetFiles(curveDirectory, "*.csv");

                    foreach (string filePath in csvFiles)
                    {
                        if (filePath.Contains("_Save"))
                            continue;

                        // 提取文件名和扩展名
                        string fileName = Path.GetFileNameWithoutExtension(filePath);
                        string extension = Path.GetExtension(filePath); // 如 ".csv"

                        // 构建新文件名：原文件名 + "_Save" + 扩展名
                        string newFileName = $"{fileName}_Save{extension}";
                        string newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName);

                        // 调用方法读取文件数据
                        Dictionary<string, string[]> csvData = await CsvReaderHelper.ReadCsv(filePath, "x");

                        string[] strings = fileName.Split('_');

                        try
                        {
                            // 重命名文件（如果已存在则跳过或覆盖）
                            if (!File.Exists(newFilePath))
                            {
                                // 移除文件
                                File.Move(filePath, newFilePath);

                                TraceClinceCurve traceClinceCurve = new TraceClinceCurve()
                                {
                                    Force = string.Join(",", csvData["x"]),
                                    Displacement = string.Join(",", csvData["y"]),
                                    TraceId = strings[0],
                                    PointName = strings[1],
                                    Staion = strings[3],
                                };

                                orderDao.SaveClinchCurve(traceClinceCurve);
                            }
                            else
                            {
                                Tools.ProduceLogTextError($"文件已存在，跳过: {newFileName}");

                                File.Delete(filePath);
                            }
                        }
                        catch (IOException ex)
                        {
                            Tools.ProduceLogTextError($"标签打入失败: {ex.Message}");
                        }
                    }
                }
                catch (Exception e)
                {

                }
            }
        }

        private async Task ClinchInfo(string directory)
        {
            if (Directory.Exists(directory))
            {
                try
                {
                    // 获取目录下所有CSV文件路径
                    string[] csvFiles = Directory.GetFiles(directory, "*.csv");

                    foreach (string filePath in csvFiles)
                    {
                        if (filePath.Contains("_Save"))
                            continue;

                        // 提取文件名和扩展名
                        string fileName = Path.GetFileNameWithoutExtension(filePath);
                        string extension = Path.GetExtension(filePath); // 如 ".csv"

                        // 构建新文件名：原文件名 + "_Save" + 扩展名
                        string newFileName = $"{fileName}_Save{extension}";
                        string newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName);

                        // 调用方法读取文件数据
                        Dictionary<string, string[]> csvData = await CsvReaderHelper.ReadCsv(filePath, "二维码");

                        List<TraceClinch> traceClinches = new List<TraceClinch>();

                        // 实例化存储类
                        TraceClinch traceClinch = null;

                        // 循环存储
                        for (int i = 0; i <= csvData["二维码"].Length - 1; i++)
                        {
                            string dateString = $"{csvData["日期"][i]} {csvData["时间"][i]}";
                            string format = "yyyyMMdd HH:mm:ss";

                            // 使用固定区域性确保格式解析稳定
                            DateTime date11 = DateTime.ParseExact(
                                dateString,
                                format,
                                CultureInfo.InvariantCulture
                            );

                            traceClinch = new TraceClinch();

                            traceClinch.Result = csvData["结果"][i];

                            traceClinch.DataTime = date11.ToString();

                            traceClinch.Pressure = csvData["压力"][i];

                            traceClinch.PressureMax = csvData["压力上限"][i];

                            traceClinch.PressureMin = csvData["压力下限"][i];

                            traceClinch.Displacement = csvData["位移量"][i];

                            traceClinch.DisplacementMax = csvData["位移上限"][i];

                            traceClinch.DisplacementMin = csvData["位移下限"][i];

                            traceClinch.TraceId = csvData["二维码"][i];

                            traceClinch.PointNo = csvData["点位编号"][i];

                            traceClinch.PointCount = csvData["点位计数"][i];

                            traceClinch.ToolNo = csvData["枪号"][i];

                            traceClinch.Station = csvData["工位号"][i];

                            traceClinches.Add(traceClinch);

                            // 调用存储
                            if (!orderDao.ClinchDataIsSave(traceClinch.TraceId, traceClinch.PointCount, traceClinch.Station))
                                orderDao.SaveClinchData(traceClinch);
                        }

                        if (traceClinch == null)
                            continue;

                        Tools.ProduceLogText($"成功保存{csvData["二维码"].Length}条压铆数据，关联码为[{traceClinch.TraceId}],工位[{traceClinch.Station}]");

                        try
                        {
                            // 重命名文件（如果已存在则跳过或覆盖）
                            if (!File.Exists(newFilePath))
                            {
                                // 移除文件
                                File.Move(filePath, newFilePath);

                                // 推送单件绑定
                                ViewService.CodeBandingOrder(traceClinch.Station, traceClinch.TraceId);

                                _ = Task.Run(() => { ViewService.InsertLineMesData(traceClinch.TraceId, traceClinch.Station, traceClinches); });

                                exitService.OrderProduction(traceClinch.Station);

                                // 过站信息绑定,获取结果
                                string result = fileName.Split('_')[2];

                                if ((traceClinch.Station == "OP50L1") || (traceClinch.Station == "OP60L1") ||
                                   (traceClinch.Station == "OP70L1") || (traceClinch.Station == "OP80L1") ||
                                   (traceClinch.Station == "OP50L2") || (traceClinch.Station == "OP60L2") ||
                                   (traceClinch.Station == "OP70L2") || (traceClinch.Station == "OP80L2") ||
                                   (traceClinch.Station == "OP50R1") || (traceClinch.Station == "OP50R2") ||
                                   (traceClinch.Station == "OP60R1") || (traceClinch.Station == "OP60R2") ||
                                   (traceClinch.Station == "OP70R1") || (traceClinch.Station == "OP70R2") ||
                                   (traceClinch.Station == "OP80R1") || (traceClinch.Station == "OP80R2")
                                   )
                                {
                                    continue;
                                }

                                if (!orderDao.ProcessDataFromCsvIsSave(traceClinch.TraceId, traceClinch.Station))
                                {
                                    PartProcess partProcess = orderDao.SaveProcessDataFromCsv(traceClinch, result);

                                    OrderStatus orderStatus = Tools.GetOrder(traceClinch.Station, traceClinch.TraceId, orderDao);

                                    ViewService.CodeBandingStationPush(partProcess, orderStatus);
                                }
                            }
                            else
                            {
                                Tools.ProduceLogTextError($"文件已存在，跳过: {newFileName}");

                                File.Delete(filePath);
                            }
                        }
                        catch (IOException ex)
                        {
                            Tools.ProduceLogTextError($"标签打入失败: {ex.Message}");
                        }
                    }
                }
                catch (DirectoryNotFoundException)
                {
                    Tools.ProduceLogTextError($"压铆数据文件目录不存在: {directory}");
                }
                catch (UnauthorizedAccessException)
                {
                    Tools.ProduceLogTextError("压铆数据文件没有访问权限，请检查凭据。");
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogTextError($"压铆数据文件读取发生错误: {ex.Message}");
                }
            }
        }

        public async Task ReadFdsData()
        {

            try
            {
                while (true)
                {
                    string folderPath = $@"D:\FDS";

                    // 获取目录下所有CSV文件路径
                    string[] xmlFiles = Directory.GetFiles(folderPath, "*.xml").Where(x => !x.Contains("_Save")).ToArray();

                    foreach (var filePath in xmlFiles)
                    {
                        await Task.Delay(200);

                        if (filePath.Contains("_Save"))
                            continue;

                        List<TraceFDS> traceFdses = new List<TraceFDS>();

                        List<TraceFDSKey> traceFDSKeys = new List<TraceFDSKey>();

                        // 提取文件名和扩展名
                        string fileName = Path.GetFileNameWithoutExtension(filePath);

                        string extension = Path.GetExtension(filePath); // 如 ".csv"

                        // 构建新文件名：原文件名 + "_Save" + 扩展名
                        string newFileName = $"{fileName}_Save{extension}";

                        string newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName);

                        XDocument doc = XDocument.Load(filePath);

                        XElement root = doc.Root;

                        // 获取扭矩过程值
                        string[] torqueData = root.Element("torque")?.Element("values")?.Value
                                                  .Split(';');

                        // 获取步序过程值
                        string[] processstepData = root.Element("processstep")?.Element("values")?.Value
                                                       .Split(';')
                                                       .ToArray();

                        // 获取穿透深度过程值
                        string[] penetrationdepthData = root.Element("penetrationdepth")?.Element("values")?.Value
                                                            .Split(';');

                        // 获取重叠量过程值
                        string[] overlapData = root.Element("overlap")?.Element("values")?.Value
                                                                       .Split(';');

                        // 获取速度过程值
                        string[] actualspeedData = root.Element("actualspeed")?.Element("values")?.Value
                                                                               .Split(';');

                        // 获取压力过程值
                        string[] joiningunitforceData = root.Element("joiningunitforce")?.Element("values")?.Value
                                                                               .Split(';');

                        // 获取工位号
                        string station = root.Element("module_name")?.Value;

                        // 获取追溯码
                        string code = root.Element("trace_tag")?.Value.Trim();

                        Dictionary<string, List<string>> processstepDics = Tools.GetArrayIndex(processstepData);

                        foreach (var processstepDic in processstepDics)
                        {
                            if (string.IsNullOrEmpty(processstepDic.Key))
                                continue;

                            TraceFDS traceFDS = new TraceFDS();

                            // 设置基础参数
                            traceFDS.Station = station;

                            traceFDS.SpotName = root.Element("spot_name")?.Value;

                            traceFDS.Result = root.Element("spot_ok").Value.Equals("1") ? "OK" : "NG";

                            traceFDS.Step = processstepDic.Key;

                            List<string> stepTorque = new List<string>();

                            List<string> stepDepth = new List<string>();

                            List<string> stepSpeed = new List<string>();

                            List<string> stepForce = new List<string>();

                            string[] strings = processstepDic.Value.ToArray();

                            for (global::System.Int32 i = 0; i < strings.Length; i++)
                            {
                                // 1. 验证索引格式
                                if (!int.TryParse(strings[i], out int dataIndex))
                                {
                                    Tools.ProduceLogTextError($"无效索引格式: {strings[i]} (位置:{i})");
                                    continue;
                                }

                                // 2. 检查扭矩数据索引边界
                                if (dataIndex < 0 || dataIndex >= torqueData.Length)
                                {
                                    Tools.ProduceLogTextError($"扭矩索引越界: {dataIndex} (最大:{torqueData.Length - 1})");
                                    continue;
                                }

                                // 3. 检查深度数据索引边界
                                if (dataIndex < 0 || dataIndex >= penetrationdepthData.Length)
                                {
                                    Tools.ProduceLogTextError($"深度索引越界: {dataIndex} (最大:{penetrationdepthData.Length - 1})");
                                    continue;
                                }

                                // 4. 检查速度数据索引边界
                                if (dataIndex < 0 || dataIndex >= actualspeedData.Length)
                                {
                                    Tools.ProduceLogTextError($"速度索引越界: {dataIndex} (最大:{actualspeedData.Length - 1})");
                                    continue;
                                }

                                // 5. 检查压力数据索引边界
                                if (dataIndex < 0 || dataIndex >= joiningunitforceData.Length)
                                {
                                    Tools.ProduceLogTextError($"压力索引越界: {dataIndex} (最大:{joiningunitforceData.Length - 1})");
                                    continue;
                                }

                                // 获取当前步序的扭矩参数
                                stepTorque.Add(torqueData[int.Parse(strings[i])]);

                                // 获取当前步序的深度参数
                                stepDepth.Add(penetrationdepthData[int.Parse(strings[i])]);

                                // 获取当前步序的速度参数
                                stepSpeed.Add(actualspeedData[int.Parse(strings[i])]);

                                // 获取当前步序的压力参数
                                stepForce.Add(joiningunitforceData[int.Parse(strings[i])]);
                            }

                            traceFDS.Torque = stepTorque.Select(x => double.Parse(x)).Average().ToString();

                            traceFDS.TorqueMax = stepTorque.Select(x => double.Parse(x)).Max().ToString();

                            traceFDS.Depth = stepDepth.Select(x => double.Parse(x)).Max().ToString();

                            traceFDS.Angle = Tools.CalculateStepAngle(stepSpeed).ToString();

                            List<string> keys = MappingTable.GetFDSDataName(processstepDic.Key);

                            if (keys?.Count > 0)
                            {

                                foreach (string key in keys)
                                {
                                    TraceFDSKey traceFDSKey = new TraceFDSKey();

                                    traceFDSKey.Step = processstepDic.Key;

                                    traceFDSKey.SpotName = root.Element("spot_name")?.Value;

                                    traceFDSKey.Station = station;

                                    // 设置关键参数
                                    switch (key)
                                    {
                                        case "速度":
                                            traceFDSKey.Key = "速度";

                                            traceFDSKey.Value = stepSpeed.Select(x => double.Parse(x)).Average().ToString();
                                            break;
                                        case "压力":
                                            traceFDSKey.Key = "压力";

                                            traceFDSKey.Value = stepForce.Select(x => double.Parse(x)).Average().ToString();
                                            break;
                                        case "深度":
                                            traceFDSKey.Key = "深度";

                                            traceFDSKey.Value = stepDepth.Select(x => double.Parse(x)).Average().ToString();
                                            break;
                                        case "转速":
                                            traceFDSKey.Key = "转速";

                                            traceFDSKey.Value = stepSpeed.Select(x => double.Parse(x)).Average().ToString();
                                            break;
                                        case "扭矩":
                                            traceFDSKey.Key = "扭矩";

                                            traceFDSKey.Value = stepTorque.Select(x => double.Parse(x)).Average().ToString();
                                            break;
                                    }

                                    if (string.IsNullOrEmpty(traceFDSKey.Value))
                                        continue;

                                    traceFDSKey.TraceId = code;
                                    traceFDSKeys.Add(traceFDSKey);
                                }
                            }

                            traceFDS.TraceId = code;
                            traceFdses.Add(traceFDS);
                        }

                        orderDao.FdsKetSave(traceFDSKeys, code);
                        orderDao.FdsSave(traceFdses, code);

                        try
                        {
                            // 重命名文件（如果已存在则跳过或覆盖）
                            if (!File.Exists(newFilePath))
                            {
                                // 移除文件
                                File.Move(filePath, newFilePath);
                            }
                            else
                            {
                                Tools.ProduceLogTextError($"文件已存在，跳过: {newFileName}");

                                File.Delete(fileName);
                            }
                        }
                        catch (Exception ex)
                        {
                            Tools.ProduceLogTextError($"FDS标签打入失败: {ex.Message}");
                        }
                    }
                    await Task.Delay(1000);
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"存储FDS数据出现异常，原因是{ex.Message}");
            }
        }
    }
}
